package com.project.petLossSystem.controller.system;

import cn.hutool.captcha.ShearCaptcha;
import com.project.petLossSystem.common.Constants;
import com.project.petLossSystem.common.ServiceResultEnum;
import com.project.petLossSystem.service.PetPostService;
import com.project.petLossSystem.service.UserService;
import com.project.petLossSystem.util.MD5Util;
import com.project.petLossSystem.util.Result;
import com.project.petLossSystem.util.ResultGenerator;
import com.project.petLossSystem.vo.UserVO;
import com.project.petLossSystem.vo.petPost.IndexPetPostVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Controller
public class SystemUserController {
    @Autowired
    private UserService userService;

    @Autowired
    private PetPostService petPostService;

    @GetMapping({"/login", "/login.html"})
    public String login() {
        return "/pc/system/login";
    }

    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestParam("loginId") String loginId,
                        @RequestParam("loginPassword") String loginPassword,
                        @RequestParam("verifyCode") String verifyCode,
                        HttpSession session) {
        if (!StringUtils.hasText(loginId)) {
            return ResultGenerator.failureResult("账号不能为空！");
        } else if (!StringUtils.hasText(loginPassword)) {
            return ResultGenerator.failureResult("密码不能为空！");
        } else if (!StringUtils.hasText(verifyCode)) {
            return ResultGenerator.failureResult("验证码不能为空！");
        }
        // 验证码
        ShearCaptcha shearCaptcha = (ShearCaptcha) session.getAttribute(Constants.VERIFY_CODE_KEY);
        session.removeAttribute(Constants.VERIFY_CODE_KEY); // 删除节省内存，删除不存在的也没事
        if(shearCaptcha == null || !shearCaptcha.verify(verifyCode)){
            return ResultGenerator.failureResult("验证码错误！");
        }
        // 不用cookie，放弃（不会弄，太麻烦，改为拦截器刷新session）
        String result = userService.login(loginId, MD5Util.MD5Encode(loginPassword, "UTF-8"), session);
        if (result.equals(ServiceResultEnum.SUCCESS.getResult())) {
            // 超时时间
            session.setMaxInactiveInterval(Constants.USER_SESSION_EXPIRE);
            return ResultGenerator.successResult();
        } else {
            return ResultGenerator.failureResult(result);
        }
    }

    @GetMapping("/register")
    public String register() {
        return "/pc/system/register";
    }

    @PostMapping("/register")
    @ResponseBody
    public Result register(@RequestParam("loginId") String loginId,
                           @RequestParam("loginPassword") String loginPassword,
                           @RequestParam("verifyCode") String verifyCode,
                           HttpSession session) {
        if (!StringUtils.hasText(loginId)) {
            return ResultGenerator.failureResult("账号不能为空！");
        } else if (!StringUtils.hasText(loginPassword)) {
            return ResultGenerator.failureResult("密码不能为空！");
        } else if (!StringUtils.hasText(verifyCode)) {
            return ResultGenerator.failureResult("验证码不能为空！");
        }
        // 验证码
        ShearCaptcha shearCaptcha = (ShearCaptcha) session.getAttribute(Constants.VERIFY_CODE_KEY);
        session.removeAttribute(Constants.VERIFY_CODE_KEY); // 删除节省内存，删除不存在的也没事
        if(shearCaptcha == null || !shearCaptcha.verify(verifyCode)){
            return ResultGenerator.failureResult("验证码错误！");
        }
        String result = userService.register(loginId, MD5Util.MD5Encode(loginPassword, "UTF-8"));
        if (result.equals(ServiceResultEnum.SUCCESS.getResult())) {
            return ResultGenerator.successResult();
        } else return ResultGenerator.failureResult(result);
    }

    @GetMapping("/profile")
    public String profile(HttpSession session, Model model) {
        // 获取个人帖子
        List<IndexPetPostVO> indexPetPostVOS = petPostService.getSelfPosts(session);
        model.addAttribute("selfPost", indexPetPostVOS);
        return "/pc/system/profile";
    }

    @PutMapping("/profile/updateNameAndIntroduction")
    @ResponseBody
    public Result updateNameAndIntroduction(@RequestParam("userName") String userName, @RequestParam("userIntroduction") String userIntroduction, HttpSession session) {
        if(!StringUtils.hasText(userName) || !StringUtils.hasText(userIntroduction)){
            return ResultGenerator.failureResult("参数不能为空！");
        }
        if(userService.updateNameAndIntroduction(userName, userIntroduction, session)){
            return ResultGenerator.successResult();
        }else return ResultGenerator.failureResult("修改失败！");
    }

    @PutMapping("/profile/updatePassword")
    @ResponseBody
    public Result updatePassword(@RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword, HttpSession session){
        if(!StringUtils.hasText(oldPassword) || !StringUtils.hasText(newPassword)){
            return ResultGenerator.failureResult("参数不能为空！");
        }
        String result = userService.updatePassword(oldPassword, newPassword, session);
        if(result.equals(ServiceResultEnum.SUCCESS.getResult())){
            session.removeAttribute("user");
            return ResultGenerator.successResult();
        }else return ResultGenerator.failureResult(result);
    }

    @GetMapping("/profile/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "/pc/system/login";
    }

    @PostMapping("/profile/img")
    @ResponseBody
    public Result img(@RequestParam("Image") MultipartFile file, HttpSession session){
        Long userId = ((UserVO) session.getAttribute("user")).getUserId();
        File image = null;
        try {
            // 判断是否是图片类型
            if (ImageIO.read(file.getInputStream()) == null) {
                return ResultGenerator.failureResult("请上传图片！");
            }
            // 用户文件夹
            File directory = new File(Constants.File_IMAGE_UPLOAD_DIC + Constants.PROFILE_USER_URL + userId);
            if (!directory.exists()) {
                directory.mkdirs(); // 不存在则新建
            }
            // 文件通用日期格式名
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.DATE_FORMAT_FILE_NAME);
            // 获取文件后缀名
            String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            StringBuilder newFileName = new StringBuilder();
            newFileName.append(simpleDateFormat.format(new Date()))
                    .append("_")
                    .append(new Random().nextInt(100))
                    .append(suffixName);
            // 创建文件
            image = new File( directory.getAbsolutePath() + "/" + newFileName.toString());
            // 复制并输出内容到新文件
            file.transferTo(image);
            // 获取存入数据库的url名
            String path = image.getAbsolutePath();
            String imageUrl = path.substring(path.indexOf(Constants.PROFILE_USER_LOCAL_URL)); // 需要换本地路径
            imageUrl = imageUrl.replaceAll("\\\\", "/"); // 得把反斜杠转正斜杠
            // 更新数据库
            if (userService.updateImg(imageUrl, userId, session)) {
                return ResultGenerator.successResult();
            } else {
                // 删除文件
                if (image != null) image.delete();
                return ResultGenerator.failureResult("更换头像失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 删除文件
            if (image != null) image.delete();
        }
        return ResultGenerator.failureResult("系统错误！");
    }
}
